<script lang="jsx" setup>
import { getCurrentInstance, ref, watch } from 'vue';
import { Input, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { useAuthStore } from '@/store/modules/auth';
import Modal from '@/components/common/modal.vue';
import { get, post } from '@/service/api/api';
import underReview from '@/assets/imgs/examine-icon/under-review.png';
import unaudited from '@/assets/imgs/examine-icon/unaudited.png';
import audited from '@/assets/imgs/examine-icon/audited.png';

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => false
  },
  operateType: {
    type: String,
    default: 'add'
  },
  rowData: {
    type: Object,
    default: null
  }
});
const authStore = useAuthStore();
const instance = getCurrentInstance();

console.log('authStore :>> ', authStore);
console.log('props :>> ', props);
const emit = defineEmits(['addModalClose', 'addSuccess']);

const lotType = ref('searchInput');
const lotids = ref([]);
const topFormList = ref([
  {
    type: 'tabs',
    span: 24,
    name: '基础信息'
  },
  {
    type: lotType,
    key: 'lotId',
    label: 'Lot号',
    span: 8,
    rule: {
      required: true,
      message: '请输入Lot号',
      trigger: 'change'
    },
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    disabled: false,
    selectOptions: lotids,
    showSelectOtherBtn: true,
    selectOtherBtnText: '查询',
    search: true,
    handleSelectOtherBtnClick: () => {
      getTableData('/rcerp/agv/erp/findByLotNo', {
        lotNumber: model.value.lotId
      });
    },
    handleSearch() {
      getTableData('/rcerp/agv/erp/findByLotNo', {
        lotNumber: model.value.lotId
      });
    }
  },

  {
    type: 'searchInput',
    key: 'moduleNo',
    label: '生产型号',
    span: 8,
    rule: {
      required: true,
      message: '请输入生产型号',
      trigger: 'change'
    },
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    handleSearch() {
      getTableData(
        '/rcerp/agv/erp/findByModuleNo',
        {
          moduleNo: model.value.moduleNo
        },
        true
      );
    }
  },
  {
    type: 'datePicker',
    key: 'modifyTime',
    label: '时间',
    span: 8,
    rule: {
      required: true,
      message: '请选择进板时间',
      trigger: 'change'
    },
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    showTime: true
  },

  {
    type: 'input',
    key: 'copperFoilFactory',
    label: '铜箔厂家',
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    span: 6
  },

  {
    type: 'input',
    key: 'copperFoilType',
    label: '铜箔类型',
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    span: 6
  },
  {
    type: 'radio',
    key: 'shiftType',
    label: '班别',
    span: 6,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    selectOptions: [
      {
        label: '白班',
        value: '0'
      },
      {
        label: '夜班',
        value: '1'
      }
    ],
    rule: {
      required: true,
      message: '请选择班别',
      trigger: 'blur'
    }
  },
  {
    type: 'radio',
    key: 'result',
    label: '判定',
    span: 6,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    selectOptions: [
      {
        label: 'ACC',
        value: 'ACC'
      },
      {
        label: 'REJ',
        value: 'REJ'
      }
    ]
  },
  {
    type: 'textarea',
    key: 'remark',
    label: '备注',
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    textareaRows: 1,
    span: 24
  },

  {
    type: 'tabs',
    span: 24,
    name: '状态信息'
  },

  {
    type: 'input',
    key: 'operator',
    label: '操作员',
    defaultValue: authStore.userInfo.user.nickName || authStore.userInfo.user.userName,
    disabled: true,
    span: 8
  },
  {
    type: 'input',
    key: 'foreman',
    label: '领班审核',
    disabled: true,
    span: 8
  },
  {
    type: 'input',
    key: 'examiner',
    label: '主管审核',
    disabled: true,
    span: 8
  },

  {
    type: 'tabs',
    span: 24,
    name: '质量项目'
  }
]);

const modelVisible = ref(props.visible);
const modleAddLoading = ref(false);
const topFormRef = ref(null);

function getModel(arr) {
  const obj = {};
  arr.forEach(item => {
    obj[item.key] = item.defaultValue || null;
    if (props?.rowData) {
      obj[item.key] = props?.rowData?.[item.key];
    }
    if (item.tansfromDisabled) {
      item.disabled = item.tansfromDisabled(props.operateType);
    }
  });
  return obj;
}

const model = ref(getModel(topFormList.value));
const tableData = ref([]);
async function handleOk(type) {
  const form = { ...topFormRef.value };
  await form.validateForm();

  const params = {
    ...model.value
  };
  const msgObj = {
    add: '新增',
    edit: '修改'
  };
  let url = '/qms/agv/press/ppProduce/insert';
  params.time = dayjs(model.value.modifyTime).format('YYYY-MM-DD HH:mm:ss');
  if (props.rowData) {
    params.createTime = model.value.modifyTime;
    params.id = props.rowData.id;
    url = '/qms/agv/press/ppProduce/update';
  }
  params.ppDataList = tableData.value;
  modleAddLoading.value = true;
  post(url, params)
    .then(({ error }) => {
      if (!error) {
        message.success(`${msgObj[props.operateType]}成功`);
        const obj = { ...instance.parent.refs.commonSearchRef, ...instance.parent.refs.tableRef };
        obj.formReset();
        obj.tableSelectChange([]);
        handleClose();
      }
    })
    .finally(() => {
      modleAddLoading.value = false;
    });
}

function handleClose() {
  modelVisible.value = false;
  lotType.value = 'searchInput';
  lotids.value = [];
  model.value = getModel(topFormList.value);
  emit('addModalClose');
}

const columnChecks = [
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 70,
    align: 'center'
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: 'pp厂家',
    align: 'center',
    customRender: ({ record }) => {
      if (props.operateType === 'look') {
        return record.ppFactory;
      }
      return (
        <Input
          value={record.ppFactory}
          onChange={e => {
            record.ppFactory = e.target.value;
          }}
        ></Input>
      );
    }
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: 'ppTG值',
    align: 'center',
    customRender: ({ record }) => {
      if (props.operateType === 'look') {
        return record.ppTgValue;
      }
      return (
        <Input
          value={record.ppTgValue}
          onChange={e => {
            record.ppTgValue = e.target.value;
          }}
        ></Input>
      );
    }
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: 'pp是否有卤素',
    align: 'center',
    customRender: ({ record }) => {
      if (props.operateType === 'look') {
        return record.isHalogen;
      }
      return (
        <Input
          value={record.isHalogen}
          onChange={e => {
            record.isHalogen = e.target.value;
          }}
        ></Input>
      );
    }
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: '使用pp规格',
    align: 'center',
    customRender: ({ record }) => {
      if (props.operateType === 'look') {
        return record.specification;
      }
      return (
        <Input
          value={record.specification}
          onChange={e => {
            record.specification = e.target.value;
          }}
        ></Input>
      );
    }
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: '批次号',
    align: 'center',
    customRender: ({ record }) => {
      if (props.operateType === 'look') {
        return record.batchId;
      }
      return (
        <Input
          value={record.batchId}
          onChange={e => {
            record.batchId = e.target.value;
          }}
        ></Input>
      );
    }
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: '含胶量',
    align: 'center',
    customRender: ({ record }) => {
      if (props.operateType === 'look') {
        return record.gelContent;
      }
      return (
        <Input
          value={record.gelContent}
          onChange={e => {
            record.gelContent = e.target.value;
          }}
        ></Input>
      );
    }
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: '使用pp数量',
    align: 'center',
    customRender: ({ record }) => {
      if (props.operateType === 'look') {
        return record.number;
      }
      return (
        <Input
          value={record.number}
          onChange={e => {
            record.number = e.target.value;
          }}
        ></Input>
      );
    }
  }
];

const loading = ref(false);

function getTableData(url, params, isModuleNo) {
  loading.value = true;
  get(url, params)
    .then(({ data, error }) => {
      if (!error) {
        data.ppDataList.forEach((item, index) => {
          item.index = index + 1;
        });
        tableData.value = data.ppDataList;
        Object.keys(model.value).forEach(item => {
          model.value[item] = data[item] || model.value[item];
        });
        if (isModuleNo) {
          lotType.value = 'select';
          lotids.value = data.lotNo.map(item => {
            return {
              label: item.lotNo,
              value: item.lotNo
            };
          });
        }
      }
    })
    .finally(() => (loading.value = false));
}

watch(
  () => props.visible,
  val => {
    modelVisible.value = val;
    if (val) {
      topFormList.value.forEach(item => {
        if (item.tansfromDisabled) {
          item.disabled = item.tansfromDisabled(props.operateType);
        }
      });
      Object.keys(model.value).forEach(item => {
        if (props.rowData) {
          model.value[item] = props.rowData[item];
        } else {
          model.value[item] = item.defaultValue || null;
        }
      });

      if (props.operateType !== 'add') {
        model.value.modifyTime = props.rowData.createTime;
      }
    }
  },
  {
    deep: true,
    immediate: true
  }
);
</script>

<template>
  <Modal
    v-model:visible="modelVisible"
    :title="`PP生产记录表${{ add: '新增', edit: '编辑', look: '查看' }[props.operateType]}`"
    height="90vh"
    width="70vw"
    :destroy-on-close="true"
    :centered="true"
    @close="handleClose"
  >
    <div class="single-FQC-add-form h-full">
      <div v-if="props.operateType !== 'add'" class="state">
        <template v-if="props.rowData.state === 0">
          <img :src="unaudited" alt="examine-icon" />
        </template>
        <template v-if="props.rowData.state === 2 || props.rowData.state === 4">
          <img :src="underReview" alt="examine-icon" />
        </template>
        <template v-if="props.rowData.state === 3">
          <img :src="audited" alt="examine-icon" />
        </template>
      </div>
      <div ref="formBoxRef" class="form w-full">
        <Form ref="topFormRef" v-model:model="model" :form-list="topFormList"></Form>
      </div>
      <ATable
        :columns="columnChecks"
        :data-source="tableData"
        bordered
        size="small"
        :loading="loading"
        :pagination="false"
      />
    </div>
    <template #footer>
      <div class="modal-footer">
        <AButton v-if="props.operateType == 'add'" type="primary" :loading="modleAddLoading" @click="handleOk('add')">
          保 存
        </AButton>
        <AButton v-if="props.operateType == 'edit'" type="primary" :loading="modleAddLoading" @click="handleOk('edit')">
          修 改
        </AButton>
        <AButton @click="handleClose">关 闭</AButton>
      </div>
    </template>
  </Modal>
</template>

<style lang="scss" scoped>
.single-FQC-add-form {
  border: 1px solid #ccc;
  padding: 0 30px;
  overflow: auto;
  padding-top: 15px;
  position: relative;

  .state {
    position: absolute;
    top: 0;
    right: 100px;
    img {
      height: 80px;
    }
  }
  .add-list {
    padding: 15px;

    .row {
      .input-box {
        width: calc(100% - 165px);
      }
    }

    .my-from {
      :deep(.ant-form-item) {
        margin-bottom: 5px;
      }
    }
  }
}
</style>
